package com.htht.smartschool.service.position;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.transform.Transformers;

import com.google.protobuf.InvalidProtocolBufferException;
import com.htht.smartschool.common.service.BaseService;
import com.htht.smartschool.model.amq.Mstatus;
import com.htht.smartschool.model.card.TCard;
import com.htht.smartschool.model.fence.Gps;
import com.htht.smartschool.model.position.BeaconImg;
import com.htht.smartschool.model.position.BeaconLbsdetail;
import com.htht.smartschool.model.position.PositionData;
import com.htht.smartschool.model.position.PositionProtoBuffer;
import com.htht.smartschool.model.position.PositionProtoBuffer.msgInfo.Builder;
import com.htht.smartschool.model.tschool.TSchool;
import com.htht.smartschool.service.card.CardService;
import com.htht.smartschool.service.fence.FenceService;
import com.htht.smartschool.util.redis.RedisKeyConstant;
import com.htht.smartschool.util.redis.RedisUtil;
import com.htht.smartschool.util.redis.SSdbUtil;
import com.htht.smartschool.util.system.ConfigUtil;
import com.htht.smartschool.util.system.DateUtil;
import com.htht.smartschool.util.system.GsonUtils;
import com.htht.smartschool.util.system.PositionUtil;

public class PositionService extends BaseService{
	CardService cardService = new CardService();
	@SuppressWarnings("rawtypes")
	public List<PositionData> getHistoryPositionByStudentCode(String studentCode,Long startTime,Long endTime,String usertype) {
		TCard card = new TCard();
		card.setStudentcode(studentCode);
		List listcards= cardService.getCard(card);
		if(listcards.size()>0){
			card = (TCard) listcards.get(0);
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
			Date time = new Date(startTime);
			String nowDate =df.format(time);
			Long start = startTime/1000;
			Long end = endTime/1000;
			System.out.println("==========================");
//			List<byte[]>  set = SSdbUtil.get(RedisKeyConstant.POSITIONS_HISTORY+card.getImei()+nowDate, 1L,9999999999999L);
//			System.out.println("set.size()=========="+set.size());
			FenceService fs  =  new FenceService();
			TSchool tf = fs.getSchoolFenceByStudentCode(studentCode);
//			Date starttime = DateUtil.getStartTime();//获取早上八点时间
//			Long stime =  starttime.getTime();
//			Date endtime =  DateUtil.getEndTime();//获取晚上六点时间
//			Long etime =  endtime.getTime();
			String week = DateUtil.weekDay(time);
			String starttimeStr = nowDate + " 08:00:00";
			Date starttime = DateUtil.getDateByStr(starttimeStr);
			Long stime =  starttime.getTime();
			Date endtimeDate = new Date(endTime);
			String endtime =df.format(endtimeDate);
			String endtimeStr = endtime + " 18:00:00";
			Date endtimeMax = DateUtil.getDateByStr(endtimeStr);
			Long etime = endtimeMax.getTime();
//			System.out.println("set.get(0)=============="+set.get(0));
//			System.out.println("set.get(1)=============="+set.get(1));
			List<PositionData> list = new ArrayList<PositionData>();
			List<byte[]>  set = null;
			if(!usertype.equalsIgnoreCase("1")){//判断不为家长用户的时候
				//查询位置信息 -- 时间控制在早上八点-晚上六点 周六周日不能查询
				if(startTime >= stime && startTime <= etime && !week.equalsIgnoreCase("星期六") && !week.equalsIgnoreCase("星期日") ){
					set = SSdbUtil.get(RedisKeyConstant.POSITIONS_HISTORY+card.getImei()+nowDate, start,end);
				}else{
					PositionData po = new PositionData();
					po.setMsg("没有权限查询");
					list.add(po);
					return list;
				}
			}
			  set = SSdbUtil.get(RedisKeyConstant.POSITIONS_HISTORY+card.getImei()+nowDate, start,end);
			for (int i = 0; i < set.size(); i++) {
				PositionProtoBuffer.msgInfo msg = null;
				try {
//					System.out.println("=========================="+i);
					msg = PositionProtoBuffer.msgInfo.parseFrom(set.get(i));
					System.out.println(msg.getTime());
				} catch (InvalidProtocolBufferException e) {
					e.printStackTrace();
				}
				Long s = msg.getTime();
			    if(s >=start && s <=end){
			    	PositionData pd = new PositionData();
			    	if(msg.getType().equalsIgnoreCase("2")){
			    		System.out.println("tf.getCenter()====="+tf.getCenter());
						pd.setLonLat(tf.getCenter());
					}else{
						System.out.println("msg.getType()====="+msg.getType());
						pd.setType(msg.getType());
						System.out.println("msg.getTime()====="+msg.getTime());
				    	pd.setTime(msg.getTime());
				    	System.out.println("msg.getStudentcode()====="+msg.getStudentcode());
				    	pd.setStudentcode(msg.getStudentcode());
				    	System.out.println("msg.getPower()====="+msg.getPower());
				    	pd.setPower(msg.getPower());
				    	System.out.println("msg.getAddress()====="+msg.getAddress());
				    	pd.setAddress(msg.getAddress());
				    	System.out.println("msg.getImei()====="+msg.getImei());
				    	pd.setImei(msg.getImei());
				    	System.out.println("card.getCellphone()====="+card.getCellphone());
				    	pd.setCellphone(card.getCellphone());
				    	System.out.println("msg.getRemark()====="+msg.getRemark());
				    	pd.setRemark(msg.getRemark());
				    	System.out.println("msg.getLonLat()========="+msg.getLonLat());
				    	if(!msg.getLonLat().equals("")&&!msg.getLonLat().equals("0.0,0.0")){
				    		pd.setLonLat(getGcjLonLat(msg.getLonLat()));
				    		list.add(pd);
				    	}
					}
			    }
			}
			if(list.size() >0){
				PositionData pd = getPositionByStudentCode(studentCode);
				System.out.println("坐标====="+pd.getLonLat());
				if(pd.getLonLat() != null){
					 if(pd.getTime() >=start &&  pd.getTime() <=end){
				    	  list.add(pd);
				      }
				}
				
			}
			return list;
		}else{
			return null;
		}
	}
	public String getGcjLonLat(String lonlat){
		String[] points =  lonlat.split(",");
		Gps g = PositionUtil.gps84_To_Gcj02(Double.valueOf(points[0]),Double.valueOf(points[1]));
		if(g == null){
			return null;
		}else{
			return g.toString();
		}
	}
	@SuppressWarnings("unchecked")
	public BeaconImg getBeaconImg(String buildid,String floor){
		BeaconImg bi = null;
		String s = RedisUtil.getInstance().getString(RedisKeyConstant.BEACONIMGOBJ+buildid+floor);
		if(s != null && s.length()>0){
			bi = (BeaconImg) GsonUtils.getInstance().fromJson(s, BeaconImg.class);
		}
		Map<String, String> map = new HashMap<String, String>();
		map.put("buildid", buildid);
		map.put("floor", floor);
		String sql = "SELECT * FROM t_beacon_img tbi WHERE tbi.build_id = '"+buildid+"' AND tbi.floor = '"+floor+"'";
		List<BeaconImg> list = getDao().getSession().createSQLQuery(sql).setResultTransformer(Transformers.aliasToBean(BeaconImg.class)).list();
		getDao().closeSession();
		if(list.size()>0){
			bi = list.get(0);
			RedisUtil.getInstance().setString(RedisKeyConstant.BEACONIMGOBJ+buildid+floor,GsonUtils.getInstance().toJson(bi));
		}
		return bi;
	}
	@SuppressWarnings("rawtypes")
	public PositionData getPositionByStudentCode(String studentCode) {
		TCard card = new TCard();
		card.setStudentcode(studentCode);
		List listcards= cardService.getCard(card);
		if(listcards.size()>0){
			card = (TCard) listcards.get(0);
			String mstatusJson = RedisUtil.getInstance().getString(RedisKeyConstant.MSTATUS+card.getImei());
			Mstatus mstatus = (Mstatus) GsonUtils.getInstance().fromJson(mstatusJson, Mstatus.class);
			String positionJson = RedisUtil.getInstance().getString(RedisKeyConstant.POSITIONS_NOW+card.getImei());
			PositionProtoBuffer.msgInfo.Builder msg = (PositionProtoBuffer.msgInfo.Builder) GsonUtils.getInstance().fromJson(positionJson, PositionProtoBuffer.msgInfo.Builder.class);
			if(msg != null){
				if(mstatus == null){
					msg.setPower("6");
				}else{
					msg.setPower(mstatus.getVlContent());
				}
				PositionData pd = new PositionData();
				pd.setType(msg.getType());
		    	pd.setTime(msg.getTime());
		    	pd.setStudentcode(studentCode);
		    	pd.setPower(msg.getPower());
		    	pd.setAddress(msg.getAddress());
		    	pd.setImei(msg.getImei());
		    	pd.setCellphone(card.getCellphone());
		    	pd.setRemark(msg.getRemark());
				if(msg.getType().equalsIgnoreCase("2")){
					FenceService fs  =  new FenceService();
					TSchool tf = fs.getSchoolFenceByStudentCode(studentCode);
					BeaconLbsdetail lbsdetail = (BeaconLbsdetail) GsonUtils.getInstance().fromJson(msg.getRemark(),BeaconLbsdetail.class);
					lbsdetail.setScale(ConfigUtil.getProperty("beaconurl", lbsdetail.getBuild_id()));
					pd.setRemark(GsonUtils.getInstance().toJson(lbsdetail));
					pd.setLonLat(tf.getCenter());
				}else{
					if(msg.getLonLat() != null && msg.getLonLat().length() > 0){
						pd.setLonLat(getGcjLonLat(msg.getLonLat()));
					}
				}
				return pd;
			}else{
				return null;
			}
		}else{
			return null;
		}
		
	}

	@SuppressWarnings("rawtypes")
	public PositionData updateByStudentCode(PositionData positionData) {
		//获取终端信息
		TCard card = new TCard();
		card.setStudentcode(positionData.getImei());
		List listcards= cardService.getCard(card);
		if(listcards.size()>0){
			//获取当前终端状态信息
			card = (TCard) listcards.get(0);
			String mstatusJson = RedisUtil.getInstance().getString(RedisKeyConstant.MSTATUS+card.getImei());
			Mstatus mstatus = (Mstatus) GsonUtils.getInstance().fromJson(mstatusJson, Mstatus.class);
			//获取当前位置信息
			String nowJson = RedisUtil.getInstance().getString(RedisKeyConstant.POSITIONS_NOW+card.getStudentcode());
			if(nowJson != null){
				PositionData pd = (PositionData) GsonUtils.getInstance().fromJson(nowJson, PositionData.class);
				if(mstatus == null){
					pd.setPower("6");
				}else{
					pd.setPower(mstatus.getVlContent());
				}
				
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
				Date time = new Date(pd.getTime()*1000);
				String nowDate =df.format(time);
				String key = RedisKeyConstant.POSITIONS_HISTORY+card.getStudentcode()+nowDate;
				pd.setKey(key);
				//存储前一个位置信息到ssdb作为历史轨迹
				SSdbUtil.add(key, pd.getTime(), pd.getTime()+"&"+nowJson);
				
				positionData.setCellphone(card.getCellphone());
				positionData.setKey(RedisKeyConstant.POSITIONS_NOW+card.getStudentcode());
				positionData.setImei(card.getImei());
				if(mstatus == null){
					positionData.setPower("6");
				}else{
					positionData.setPower(mstatus.getVlContent());
				}
				String json = GsonUtils.getInstance().toJson(positionData);
				//存储当前位置信息
				RedisUtil.getInstance().setString(RedisKeyConstant.POSITIONS_NOW+card.getStudentcode(),json);
				return positionData;
			}else{
				String json = GsonUtils.getInstance().toJson(positionData);
				//存储当前位置信息
				RedisUtil.getInstance().setString(RedisKeyConstant.POSITIONS_NOW+card.getStudentcode(),json);
				return positionData;
			}
		}else{
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	public List<PositionData> teacherGetStudentsPosition(PositionData positionData) {
		String sql = "SELECT tt.* FROM (SELECT ts.name, ts.studentcode, tc.classcode, ts.adress, ts.schoolid, tc.type FROM t_student ts, t_class tc WHERE tc.classcode = ts.classcode ";
		if(positionData.getClasscode() != null && positionData.getClasscode().length() > 0){
			sql += "AND tc.classcode = :classcode";
		}
		sql+= ") tt LEFT JOIN t_card ta ON tt.studentcode = ta.studentcode where 1=1";
		if(positionData.getSchoolcode() != null && positionData.getSchoolcode().length() > 0){
			sql += " and tt.schoolid = :schoolcode";
		}
		if(positionData.getSchooltype() != null && positionData.getSchooltype().length() > 0){
			sql += "  and tt.type = :schooltype";
		}
		if(positionData.getRolecode() != null && positionData.getRolecode().length() > 0){
			positionData.setRolecode(positionData.getRolecode().replace(",", "^"));
			sql = "select t1.* from ("+sql+")t1,(select * from t_data_role where rolecode in (:rolecode))t2 where t1.classcode = t2.classcode";
		}
		List<Object[]> list = getDao().queryBySQL(sql,positionData);
		List<PositionData> result = new ArrayList<PositionData>();
		for (Object[] obj : list) {
			String studentcode = String.valueOf(obj[1]);
			Date date = new Date();
			Long tt = date.getTime();//获取当前时间  转换成long类型 秒
			Date starttime = DateUtil.getStartTime();//获取早上八点时间
			Long stime =  starttime.getTime();
			Date endtime =  DateUtil.getEndTime();//获取晚上六点时间
			Long etime =  endtime.getTime();
			String week = DateUtil.weekDay(null);
			//查询位置信息 -- 时间控制在早上八点-晚上六点 周六周日不能查询
			if(tt >= stime && tt <= etime && !week.equalsIgnoreCase("星期六") && !week.equalsIgnoreCase("星期日") ){
				PositionData pd = new PositionData();//查询学生定位信息
				try {
					pd = getPositionByStudentCode(studentcode);
				} catch (Exception e) {
					
				}
				if(pd == null){
					 pd = new PositionData();
					 pd.setAddress("--");
				}
				pd.setStudentname(String.valueOf(obj[0]) == "null" ? "--" :String.valueOf(obj[0]));
				pd.setStudentcode(String.valueOf(obj[1]) == "null" ? "--" :String.valueOf(obj[1]));
				pd.setFamilyphone(String.valueOf(obj[3]) == "null" ? "--" :String.valueOf(obj[3]));
				result.add(pd);	
			}
		}
		return result;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Map getSosWarn(PositionData pd) {
		String sql  = "SELECT * FROM (SELECT DISTINCT tws.*,ts.name FROM t_warn_sos tws,t_student ts WHERE tws.id > 0 AND tws.studentcode = ts.studentcode ";
		if(pd.getUsertype().equalsIgnoreCase("0")){
			sql += " and tws.remark = '4' ";
		}
		if(pd.getStudentcode() != null && pd.getStudentcode().length() > 0){
			sql +=" and tws.studentcode = :studentcode ";
		}
		if(pd.getClasscode() != null && pd.getClasscode().length() > 0){
			sql +=" and tws.classcode = :classcode ";
		}
		if(pd.getStartTime() != null && pd.getStartTime() > 0){
			sql +=" and tws.time >= :startTime ";
		}
		if(pd.getEndTime() != null && pd.getEndTime() > 0){
			sql +=" and tws.time <= :endTime ";
		}
		if(pd.getFlag() != null && pd.getFlag().length() > 0){
			sql +=" and tws.flag = :flag ";
		}
		if(pd.getSchoolcode() != null && pd.getSchoolcode().length() > 0){
			sql += " and ts.schoolid = :schoolcode";
		}
		sql += ")td ORDER BY td.flag ASC,td.time DESC";
		List<Object[]> list = getDao().queryBySqlPage(sql,pd, pd.getCurrentpage(),  pd.getPageSize());
		List<PositionData> result = new ArrayList<PositionData>();
		int total = getDao().getCountBySqlPage("select count(*) from ("+sql+")tu",pd);
		Map map = new HashMap();
		for (Object[] obj : list) {
			PositionData positiondata = new PositionData();
			positiondata.setId(String.valueOf(obj[0]));
			positiondata.setImei(String.valueOf(obj[1]));
			positiondata.setTime(Long.valueOf(String.valueOf(obj[2])));
			positiondata.setAddress(String.valueOf(obj[3]));
			positiondata.setClasscode(String.valueOf(obj[4]));
			positiondata.setStudentcode(String.valueOf(obj[5]));
			positiondata.setLonLat(String.valueOf(obj[6]));
			positiondata.setRemark(String.valueOf(obj[7]));
			positiondata.setType(String.valueOf(obj[8]));
			positiondata.setFlag(String.valueOf(obj[9]));
			positiondata.setStudentname(String.valueOf(obj[10]));
			result.add(positiondata);
		}
		map.put("list", result);
		map.put("total", total);
		return map;
	}

	@SuppressWarnings("rawtypes")
	public boolean addSosWarn(Builder positionData) {
		TCard card = new TCard();
		card.setImei(positionData.getImei());
		List listcards= cardService.getCard(card);
		Map<String,Object> params = new HashMap<String,Object>();
		if(listcards.size()>0){
			card = (TCard) listcards.get(0);
			
			String sql = "INSERT INTO t_warn_sos (id,imei,time,address,classcode,studentcode,lonlat,remark,type,flag) "
					+ "VALUES ( NULL,:imei,:time,:address,:classcode,"
					+":studentcode,:lonlat,:remark,:type,'0');";
			params.put("imei", card.getImei());
			params.put("time", positionData.getTime());
			params.put("address", positionData.getAddress());
			params.put("classcode", card.getClasscode());
			params.put("studentcode", card.getStudentcode());
			params.put("lonlat", positionData.getLonLat());
			params.put("remark",positionData.getRemark());
			params.put("type", positionData.getType());
			int i = getDao().executeSQL(sql,params);
			return i == -1 ? false : true;
		}else{
			return false;
		}
	}
	public boolean updateSosWarn(PositionData pd) {
		String[] ids = pd.getId().split(",");
		String sql = "UPDATE t_warn_sos tws SET tws.flag=:flag WHERE tws.id in (";
		for (int i = 0; i < ids.length; i++) {
			sql += "'"+ids[i]+"',";
		}
		sql = sql.substring(0, sql.length()-1);
		sql += ")";
		int i = getDao().executeSQL(sql,pd);
		return i == -1 ? false : true;
	}
}
